<!-- 日消费 -->
<template>
  <div>
    <Row>
      <Col>
        <DatePicker
          type="daterange"
          v-model="date"
          placement="bottom-end"
          placeholder="请选择时间段"
          @on-change="changeDate"
          :options="optionsdate"
          :clearable="false"
          style="width: 200px"
        ></DatePicker>
      </Col>
      <Col class="ivu-ml-16">
        <Button
          type="primary"
          @click="changeAdd('add', { id: '' })"
          v-hasC="{
            name: '-v1-marketing-consume-update-consume3',
            flag: '/v1/marketing/consume/update-consume',
          }"
          >日消费录入</Button
        >
      </Col>
    </Row>
    <div class="ivu-mt-16">
      <Table :columns="columns" :data="data" :max-height="550">
        <template slot-scope="{ row }" slot="option">
          <a
            type="primary"
            @click="changeAdd('edit', row)"
            :disabled="row.is_disabled"
            v-hasC="{
              name: '-v1-marketing-consume-update-consume4',
              flag: '/v1/marketing/consume/update-consume',
            }"
            >编辑</a
          >
          <Divider
            type="vertical"
            v-hasCC="[
              {
                name: '-v1-marketing-consume-update-consume4',
                flag: '/v1/marketing/consume/update-consume',
              },
              {
                name: '-v1-marketing-consume-delete-consume',
                flag: '/v1/marketing/consume/delete-consume',
              },
            ]"
          ></Divider>
          <a
            type="primary"
            @click="deleteTag(row)"
            :disabled="row.is_disabled"
            v-hasC="{
              name: '-v1-marketing-consume-delete-consume',
              flag: '/v1/marketing/consume/delete-consume',
            }"
            >删除</a
          >
        </template>
      </Table>
      <div
        class="ivu-mt iuv-text-center"
        style="display:flex;justify-content: center;"
      >
        <Page
          show-total
          show-elevator
          show-sizer
          :total="total"
          :current.sync="params.page"
          :page-size="params.pageSize"
          :page-size-opts="pageOpts"
          @on-change="formSize"
          @on-page-size-change="formChangePage"
        ></Page>
      </div>
    </div>
    <Modal v-model="modalStatus" :title="modalTitle" width="800">
      <Row :gutter="8">
        <Col span="8">
          <DatePicker
            class="ivu-mb-16"
            type="date"
            :disabled="isdisabled"
            v-model="consumeParams.date"
            placement="bottom-end"
            :options="optionsConsumeMonth"
            @on-change="changeChannel"
            placeholder="请选择时间"
            style="width: 200px"
          ></DatePicker>
          <List class="ivu-sidebar">
            <span
              v-for="item in consumeAllList"
              :key="item.source_channel_id"
              @click="changeTab(item.source_name)"
            >
              <ListItem
                :class="item.source_name === tabId ? 'addressactive' : ''"
                ><span style="margin-left:10px"
                  ><a
                    class="a"
                    :class="item.source_name === tabId ? 'addressactive' : ''"
                    @click="getScrollIndex('#' + item.source_name)"
                    >{{ item.source_name }}</a
                  ></span
                ></ListItem
              >
            </span>
          </List>
        </Col>
        <Col span="16" style="height: 600px;overflow: auto;">
          <div v-for="item in consumeAllList" :key="item.source_channel_id">
            <Divider
              orientation="left"
              :class="tabId == item.source_name ? 'active' : ''"
              :id="item.source_name"
              >{{ item.source_name }}</Divider
            >
            <div>
              <div
                style="display: inline-block;"
                class="ivu-mr-16"
                v-for="it in item.children"
                :key="it.source_channel_id"
              >
                <div class="ivu-mr-8 ivu-mb-8">{{ it.source_name }}</div>
                <InputNumber
                  class="ivu-mb-8"
                  :min="0"
                  v-model="it.consume"
                  placeholder="请输入"
                  v-width="100"
                ></InputNumber>
              </div>
            </div>
          </div>
        </Col>
      </Row>
      <div slot="footer">
        <Button @click="consumeCancel">取消</Button>
        <Button type="primary" @click="consumeSubmit" :disabled="disabled"
          >提交</Button
        >
      </div>
    </Modal>
  </div>
</template>
<script>
import {
  marketingconsumegetconsume,
  marketingconsumeupdateconsume,
  marketingconsumeconsumelist,
  deleteCconsume,
} from "@/api/hqapi/networkMarketing.js";
export default {
  data() {
    const optionsConsumeMonth = {
      // disabledDate(date) {
      //     return date && date.valueOf() > Date.now() - 1000 * 24 * 3600;
      // }

      disabledDate(date) {
        // console.log(date.getTime(),'111')
        // console.log(new Date().getTime(),'122')
        //前两个月之内
        return date.getTime() > new Date().getTime();
        //  return (date.getTime() < (new Date().getTime() - 4 * 24 * 60 * 60 * 1000)) || date.getMonth() < new Date().getMonth() || date.getTime() > new Date().getTime();
        // return date && ((date.getTime() + 24 * 60 * 60 * 1000 < new Date().getTime()) || date.getTime() > (new Date().getTime() + 60 * 24 * 60 * 60 * 1000));
        //  return date && (( new Date().getTime() + 60 * 24 * 60 * 60 * 1000>= Date.now()||new Date().getTime()<date.getTime() + 24 * 60 * 60 * 1000 ) );
      },
    };
    return {
      time: null,
      optionsConsumeMonth,
      // columns:[
      //   { title: "日期", key: "index",minWith:'120',fixed:'left' },
      //   { title: "百度", key: "" ,minWith:'120'},
      //   { title: "搜狗", key: "" ,minWith:'120'},
      //   { title: "神马", key: "",minWith:'120' },
      //   { title: "优化", key: "",minWith:'120' },
      //   { title: "操作", slot:'option',With:'100',fixed:'right'  },
      // ],
      columns: [],
      columnsDate: [{ title: "日期", key: "date", fixed: "left", width: 120 }],
      columnsOption: [
        { title: "操作", slot: "option", width: 120, fixed: "right" },
      ],
      columnsTitle: [],
      data: [],
      date: [],
      total: 0,
      params: { start_time: "", end_time: "", page: 1, pageSize: 20 },
      pageOpts: [10, 20, 50, 100],
      modalStatus: false,
      modalTitle: "",
      // 模态框
      tabId: "",
      sidebar: [
        { id: 1, name: "竞价", address: "1" },
        { id: 2, name: "短视频", address: "2" },
        { id: 3, name: "朋友圈", address: "3" },
        { id: 4, name: "优化", address: "4" },
      ],
      consumeParams: { date: "", channel_id: "", id: "" },
      consumeAllList: [],
      disabled: false,
      loading: false,
      isdisabled: false,
      editDisabled: false,
      optionsdate: {
        disabledDate(date) {
          return date && date.valueOf() > Date.now();
        },
      },
    };
  },
  mounted() {
    // this.$Date().startOf('month').format('YYYY-MM-DD')
    // console.log(newmonth,'newmonth')
    this.date = [
      this.$Date()
        .startOf("month")
        .format("YYYY-MM-DD"),
      this.$Date().format("YYYY-MM-DD"),
    ];
    this.params.start_time = this.date[0];
    this.params.end_time = this.date[1];
    // this.consumeMonthParams.date = this.$Date().subtract(1, 'month').format('YYYY-MM')
    this.consumeParams.date = this.$Date()
      .subtract(1, "day")
      .format("YYYY-MM-DD");
    this.askData();
  },
  methods: {
    askData() {
      // this.columns= [],
      this.loading = true;
      marketingconsumeconsumelist(this.params).then((res) => {
        this.data = res.list.list;
        this.total = res.list.total;
        this.columnsTitle = res.header_list;
        this.columns = [
          ...this.columnsDate,
          ...this.columnsTitle,
          ...this.columnsOption,
        ];
        this.loading = false;
      });
    },
    changeDate() {
      this.params.start_time = this.date[0];
      this.params.end_time = this.date[1];
      this.datemonth();
      this.askData();
    },
    // 判断日期时候近2个月
    datemonth() {
      let lastmonth = this.$Date()
        .subtract(1, "month")
        .format("YYYY-MM");
      // console.log(lastmonth,'lastmonth')
      let newmonth = this.$Date().format("YYYY-MM");
      if (
        lastmonth == this.$Date().format("YYYY-MM") ||
        this.$Date().format("YYYY-MM") == newmonth
      ) {
        this.editDisabled = false;
      } else {
        this.editDisabled = true;
      }
    },
    // index是当前索引，直接a标签href会让url改变，解决办法不要herf，使用点击事件，使用document.querySelector实现锚点的效果
    getScrollIndex(idName) {
      // console.log(idName,'idName')
      // this.active=index;
      document.querySelector(idName).scrollIntoView(true);
    },
    formSize(index) {
      this.params.page = index;
      this.askData();
    },
    formChangePage(e) {
      this.params.page = 1;
      this.params.pageSize = e;
      this.askData();
    },
    changeAdd(e, item) {
      // console.log(e,'e')
      this.modalStatus = true;
      if (e == "add") {
        this.isdisabled = false;
        this.modalTitle = "录入";
      } else {
        this.isdisabled = true;
        this.modalTitle = "编辑";
      }
      this.consumeChannel(item);
    },
    changeChannel(val) {
      this.consumeParams.date = val;
      this.consumeChannel({ id: "" });
    },
    changeTab(address) {
      console.log(address, "address");

      this.tabId = address;
    },
    // 获取日消费录入
    consumeChannel(item) {
      if (this.modalTitle == "编辑") {
        this.consumeParams.date = item.date;
      }
      // this.consumeParams.date=item.date?item.date:this.$Date().subtract(1, 'day').format('YYYY-MM-DD')
      this.consumeParams.channel_id = item.id;
      let params = {
        date:
          this.modalTitle == "编辑"
            ? item.date
            : this.$Date(this.consumeParams.date).format("YYYY-MM-DD"),
        channel_id: this.consumeParams.channel_id,
      };
      marketingconsumegetconsume(params).then((res) => {
        this.consumeParams.id = res[0].source_channel_id;
        this.tabId = res[0].source_name;
        this.consumeAllList = res;
        this.modalStatus = true;
      });
    },
    // 日消费录入保存
    consumeSubmit() {
      let list = [];
      for (let item of this.consumeAllList) {
        for (let items of item.children) {
          if ((items.consume === 0 || items.consume > 0) && !items.disabled) {
            list.push({
              id: items.id ? items.id : 0,
              date: this.$Date(this.consumeParams.date).format("YYYY-MM-DD"),
              source_channel_id: items.source_channel_id,
              consume: items.consume,
            });
          }
        }
      }
      // console.log(this.consumeAllList, list)
      this.disabled = true;
      if (list.length > 0) {
        marketingconsumeupdateconsume({ list }).then((res) => {
          this.disabled = false;
          this.$Message.success("日消费录入成功");
          // this.consumeChannel(this.consumeParams.channel_id)
          this.askData();
          this.modalStatus = false;
        });
      } else {
        this.disabled = false;
        this.$Message.error("请至少输入一项数据");
      }
    },
    consumeCancel() {
      this.disabled = false;
      this.modalStatus = false;
    },
    /* 删除 */
    deleteTag(row) {
      this.$Modal.confirm({
        title: "删除确认",
        content: "是否确认删除消费记录，删除将无法恢复",
        loading: true,
        onOk: () => {
          deleteCconsume({ date_time: row.date }).then((res) => {
            this.$Modal.remove();
            this.$Message.success("删除成功");
            this.askData();
          });
        },
      });
    },
  },
};
</script>
<style scoped>
.active {
  color: #2b85e4;
}
/deep/.ivu-list-items {
  border-left: 1px solid #ccc !important;
}
.addressactive {
  color: #2b85e4 !important;
}
.addressactive::before {
  content: "o";
  color: #2b85e4;
  position: absolute;
  left: -3px;
  font-weight: 600;
}
.a {
  color: #515a6e;
}
/* .anchor1, .anchor2{width:100px;height:100px;margin-top:2000px;margin-bottom:2000px;}
    	.anchor1{background:red;}
    	.anchor2{background:green;} */
</style>
